import * as VueRouter from 'vue-router'
import routes from "~pages";
import $store from '@/store'
import 'vue-router'

// const routes:VueRouter.RouteRecordRaw[]=[
//   { path: '/', component: () =>import(/* webpackChunkName: "main" */ '@/views/Login.vue') }
// ]
console.log('routes:',routes)
console.log('env:',import.meta.env)
const PAGE_CACHE=import.meta.env.VITE_PAGE_CACHE=='true'?true:false
const router = VueRouter.createRouter({
  //history: VueRouter.createWebHashHistory(),
  history: VueRouter.createWebHistory('/vite-vue3-shop'),
  routes,
})
const cachePages=(name) =>{
  const time=(new Date()).getTime()
  $store.commit('pages/removeExpireCache')
  if($store.getters['pages/hasCachePage'](name)) return
  $store.commit('pages/addCachePage',{
    name,time
  })
}
router.beforeEach((to:any, from:any, next) => {
  // 返回 false 以取消导航
  if(PAGE_CACHE&&to.meta.cache) cachePages(to.name)
  const roles=$store.getters['user/getRoles']
  const token=$store.getters['user/getToken']
  if(to.meta.auth&&!token){
    next({
      name:"login",
      query:{
        to:to.path
      }
    })
    return false
  }
  const authPass=roles.some((r:string) =>to.meta.roles.includes(r))
  if(to.meta.auth&&to.meta.roles.length>0&&!authPass){
    next({
      name:"forbid"
    })
    return false
  }
  next()
})
export default router